import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/modules/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'),
    children: [
      {
        path: '',
        name: 'ControlPanel',
        component: () => import('../views/dashboard/ControlPanel.vue')
      },
      {
        path: 'company',
        name: 'CompanyInfo',
        component: () => import('../views/dashboard/CompanyInfo.vue')
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../views/dashboard/Orders.vue')
      },
      {
        path: 'recruitment',
        name: 'Recruitment',
        component: () => import('../views/dashboard/Recruitment.vue'),
        children: [
          {
            path: '',
            name: 'RecruitmentDefault',
            redirect: '/dashboard/recruitment/hr-list'
          },
          {
            path: 'hr-list',
            name: 'HrList',
            component: () => import('../views/dashboard/recruitment/HrList.vue')
          },
          {
            path: 'job-history',
            name: 'JobHistory',
            component: () => import('../views/dashboard/recruitment/JobHistory.vue')
          },
          {
            path: 'interview-records',
            name: 'InterviewRecords',
            component: () => import('../views/dashboard/recruitment/InterviewRecords.vue')
          }
        ]
      }
    ]
  }
]
// 白名单
const whiteList = ['/login','/404']


const router = createRouter({
  history: createWebHistory(),
  routes
})


// 全局路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if(userStore.token){
    if (to.path === '/login') {
      next('/dashboard')
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next(`/login?redirectUrl=${to.path}`)
      }
    }
  }
})
export default router 